#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
from kivy.utils import platform

# Android相关导入
ANDROID_AVAILABLE = False
if platform == 'android':
    try:
        from jnius import autoclass
        from android.permissions import request_permissions, Permission
        from android.storage import primary_external_storage_path
        ANDROID_AVAILABLE = True
        print("Android modules loaded successfully")
    except ImportError as e:
        print(f"Android modules import failed: {e}")
        ANDROID_AVAILABLE = False
    except Exception as e:
        print(f"Android modules initialization failed: {e}")
        ANDROID_AVAILABLE = False
else:
    print(f"Not running on Android platform: {platform}")


class AndroidPermissions:
    """Android权限管理类"""
    
    def __init__(self):
        self.permissions_granted = False
        self.storage_path = None
        
    def request_storage_permissions(self, callback=None):
        """请求存储权限"""
        if not ANDROID_AVAILABLE:
            if callback:
                callback(True)  # 非Android平台默认授权
            return True
        
        try:
            # 请求必要的权限
            permissions = [
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.MANAGE_EXTERNAL_STORAGE
            ]
            
            def permission_callback(permissions, grant_results):
                granted = all(grant_results)
                self.permissions_granted = granted
                if callback:
                    callback(granted)
            
            request_permissions(permissions, permission_callback)
            
        except Exception as e:
            print(f"Permission request error: {e}")
            if callback:
                callback(False)
            return False
    
    def get_storage_paths(self):
        """获取存储路径"""
        paths = {
            'internal': None,
            'external': None,
            'downloads': None,
            'movies': None
        }
        
        if ANDROID_AVAILABLE:
            try:
                # 获取主要外部存储路径
                paths['external'] = primary_external_storage_path()
                
                # 获取其他常用目录
                Environment = autoclass('android.os.Environment')
                
                # 下载目录
                downloads_dir = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS
                )
                if downloads_dir:
                    paths['downloads'] = downloads_dir.getAbsolutePath()
                
                # 电影目录
                movies_dir = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_MOVIES
                )
                if movies_dir:
                    paths['movies'] = movies_dir.getAbsolutePath()
                
                # 内部存储
                context = autoclass('org.kivy.android.PythonActivity').mActivity
                internal_dir = context.getFilesDir()
                if internal_dir:
                    paths['internal'] = internal_dir.getAbsolutePath()
                    
            except Exception as e:
                print(f"Error getting storage paths: {e}")
        else:
            # 非Android平台的默认路径
            import os
            home = os.path.expanduser('~')
            paths['internal'] = home
            paths['external'] = home
            paths['downloads'] = os.path.join(home, 'Downloads')
            paths['movies'] = os.path.join(home, 'Videos')
        
        return paths
    
    def get_default_output_dir(self):
        """获取默认输出目录"""
        paths = self.get_storage_paths()
        
        # 优先使用Movies目录，其次是Downloads，最后是外部存储
        for key in ['movies', 'downloads', 'external', 'internal']:
            if paths[key] and os.path.exists(paths[key]):
                return paths[key]
        
        return None
    
    def create_app_directory(self, base_path=None):
        """创建应用专用目录"""
        if not base_path:
            base_path = self.get_default_output_dir()
        
        if not base_path:
            return None
        
        app_dir = os.path.join(base_path, 'VideoSplitter')
        
        try:
            os.makedirs(app_dir, exist_ok=True)
            return app_dir
        except Exception as e:
            print(f"Error creating app directory: {e}")
            return None


class AndroidFileManager:
    """Android文件管理类"""
    
    def __init__(self):
        self.permissions = AndroidPermissions()
    
    def get_video_files(self, directory):
        """获取目录中的视频文件"""
        video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.3gp']
        video_files = []
        
        try:
            if os.path.exists(directory):
                for file in os.listdir(directory):
                    file_path = os.path.join(directory, file)
                    if os.path.isfile(file_path):
                        _, ext = os.path.splitext(file.lower())
                        if ext in video_extensions:
                            video_files.append({
                                'name': file,
                                'path': file_path,
                                'size': os.path.getsize(file_path)
                            })
        except Exception as e:
            print(f"Error listing video files: {e}")
        
        return sorted(video_files, key=lambda x: x['name'])
    
    def get_recent_videos(self, limit=10):
        """获取最近的视频文件"""
        paths = self.permissions.get_storage_paths()
        recent_videos = []
        
        # 搜索常用目录
        search_dirs = []
        for key in ['movies', 'downloads', 'external']:
            if paths[key] and os.path.exists(paths[key]):
                search_dirs.append(paths[key])
        
        for directory in search_dirs:
            try:
                videos = self.get_video_files(directory)
                for video in videos:
                    video['mtime'] = os.path.getmtime(video['path'])
                    recent_videos.append(video)
            except Exception as e:
                print(f"Error scanning directory {directory}: {e}")
        
        # 按修改时间排序，返回最新的
        recent_videos.sort(key=lambda x: x['mtime'], reverse=True)
        return recent_videos[:limit]
    
    def scan_media_store(self):
        """扫描Android媒体库"""
        if not ANDROID_AVAILABLE:
            return []
        
        videos = []
        
        try:
            # 使用MediaStore查询视频文件
            MediaStore = autoclass('android.provider.MediaStore')
            ContentResolver = autoclass('android.content.ContentResolver')
            Uri = autoclass('android.net.Uri')
            
            context = autoclass('org.kivy.android.PythonActivity').mActivity
            resolver = context.getContentResolver()
            
            # 查询视频文件
            uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
            projection = [
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.DATA,
                MediaStore.Video.Media.SIZE,
                MediaStore.Video.Media.DURATION
            ]
            
            cursor = resolver.query(uri, projection, None, None, None)
            
            if cursor:
                while cursor.moveToNext():
                    name = cursor.getString(0)
                    path = cursor.getString(1)
                    size = cursor.getLong(2)
                    duration = cursor.getLong(3)
                    
                    if path and os.path.exists(path):
                        videos.append({
                            'name': name,
                            'path': path,
                            'size': size,
                            'duration': duration / 1000  # 转换为秒
                        })
                
                cursor.close()
                
        except Exception as e:
            print(f"Error scanning media store: {e}")
        
        return videos


class AndroidNotifications:
    """Android通知管理类"""
    
    def __init__(self):
        self.notification_id = 1
    
    def show_progress_notification(self, title, message, progress=0):
        """显示进度通知"""
        if not ANDROID_AVAILABLE:
            return
        
        try:
            from plyer import notification
            notification.notify(
                title=title,
                message=message,
                timeout=1
            )
        except Exception as e:
            print(f"Notification error: {e}")
    
    def show_completion_notification(self, title, message):
        """显示完成通知"""
        if not ANDROID_AVAILABLE:
            return
        
        try:
            from plyer import notification
            notification.notify(
                title=title,
                message=message,
                timeout=5
            )
        except Exception as e:
            print(f"Notification error: {e}")


def check_android_requirements():
    """检查Android环境要求"""
    requirements = {
        'platform': platform == 'android',
        'permissions_available': ANDROID_AVAILABLE,
        'storage_available': False,
        'media_store_available': False
    }
    
    if ANDROID_AVAILABLE:
        try:
            # 检查存储访问
            paths = AndroidPermissions().get_storage_paths()
            requirements['storage_available'] = any(paths.values())
            
            # 检查MediaStore访问
            MediaStore = autoclass('android.provider.MediaStore')
            requirements['media_store_available'] = True
            
        except Exception as e:
            print(f"Android requirements check error: {e}")
    
    return requirements


def get_android_info():
    """获取Android设备信息"""
    info = {
        'platform': platform,
        'android_available': ANDROID_AVAILABLE,
        'api_level': None,
        'device_model': None,
        'storage_info': None
    }
    
    if ANDROID_AVAILABLE:
        try:
            # 获取API级别
            Build = autoclass('android.os.Build$VERSION')
            info['api_level'] = Build.SDK_INT
            
            # 获取设备型号
            BuildInfo = autoclass('android.os.Build')
            info['device_model'] = f"{BuildInfo.MANUFACTURER} {BuildInfo.MODEL}"
            
            # 获取存储信息
            permissions = AndroidPermissions()
            info['storage_info'] = permissions.get_storage_paths()
            
        except Exception as e:
            print(f"Android info error: {e}")
    
    return info